<template>
  <div class="tooltip" @mouseenter="handleEnter" @mouseleave="handleLeave">
    <slot></slot>
    <teleport to="body" v-if="isShow">
      <div
        class="tooltip-content"
        :style="{ left: left + 'px', top: top + 'px' }"
        ref="tooltipContent"
      >
        <slot name="content"></slot>
      </div>
      <div
        v-if="showLeft"
        class="tooltip-content"
        :style="{ left: left - contentWidth - 10 + 'px', top: top + 'px' }"
      >
        <slot name="contentLeft"></slot>
      </div>
    </teleport>
  </div>
</template>
<script lang="ts">
import { computed, defineComponent, nextTick, ref } from "vue";

const EwgTooltip = defineComponent({
  name: "EwgTooltip",
  props: {
    showLeft: {
      type: Boolean,
      default: false
    }
  },
  setup() {
    const isShow = ref(false);
    const left = ref(0);
    const top = ref(0);
    const tooltipContent = ref();
    const handleEnter = (e: any) => {
      const { pageX, pageY } = e;
      isShow.value = true;
      left.value = pageX + 5;
      top.value = pageY + 5;
      nextTick(() => {
        if (tooltipContent.value) {
          const maxHeight = document.body.clientHeight;
          const contentHeight = tooltipContent.value.clientHeight;
          const maxWidth = document.body.clientWidth;
          const contentWidth = tooltipContent.value.clientWidth;
          if (top.value + contentHeight > maxHeight) {
            top.value = pageY - contentHeight - 5;
          }
          if (left.value + contentWidth > maxWidth) {
            left.value = pageX - contentWidth - 5;
          }
        }
      });
    };
    const contentWidth = computed(() => {
      return (tooltipContent.value && tooltipContent.value.clientWidth) || 300;
    });
    const handleLeave = () => {
      isShow.value = false;
    };
    return {
      isShow,
      left,
      top,
      handleEnter,
      handleLeave,
      tooltipContent,
      contentWidth
    };
  }
});
export default EwgTooltip;
</script>
<style lang="scss" scoped>
.tooltip {
  width: inherit;
  height: inherit;
  position: relative;
  display: inline-block;
}
.tooltip-content {
  position: absolute;
  top: 0;
  left: 0;
}
</style>
